package com.wish233.model.protocol;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;

/**
 * @author WHH
 * 解决半包黏包问题的装饰者类
 */
public class NetServerBufferHandlerWrapper implements Handler<Buffer> {

    private final RecordParser parser;

    public NetServerBufferHandlerWrapper(Handler<Buffer> bufferHandler) {
        this.parser =  initRecordParser(bufferHandler);
    }

    @Override
    public void handle(Buffer buffer) {
        //将buffer委托给RecordParser
        parser.handle(buffer);
    }

    private RecordParser initRecordParser(Handler<Buffer> bufferHandler) {
        RecordParser recordParser = RecordParser.newFixed(ProtocolConstant.MESSAGE_HEADER_LEN);
        recordParser.setOutput(new Handler<Buffer>() {
            Buffer resBuffer = Buffer.buffer();
            int size = -1;
            @Override
            public void handle(Buffer buffer) {
                if (-1 == size) {
                    //读取消息头长度
                    size = buffer.getInt(14);
                    parser.fixedSizeMode(size);
                    resBuffer.appendBuffer(buffer);
                } else {
                    //拼接body
                    resBuffer.appendBuffer(buffer);
                    //处理完整信息
                    bufferHandler.handle(resBuffer);
                    parser.fixedSizeMode(ProtocolConstant.MESSAGE_HEADER_LEN);
                    //读取下一条
                    size = -1;
                    resBuffer = Buffer.buffer();
                }
            }
        });
        return recordParser;
    }
}
